<?php

//define("INTERVAL", "- 9 days ");
define("INTERVAL_GANTT","- 200 days ");

define("PROJECT_TAG",'project');
define("SUBPROJECT_TAG",'subproject');
define("MILESTONE_TAG",'milestone');
define("LOG_TAG",'log');
        

class Date_Label
{
    public $date;
    public $days_logged;
}
class Log
{
    public $engineer; //String
    public $msg; //String
    public $days; //int
    public $recent; //flag
    public $noworkload; // is it a workload or just filler
    public $date;
}


class Milestone
{
    public $name; //String
    public $assignee;//String
    public $status; //String
    public $logs; //array
    public $recent; //flag
}

class SubProject
{
    public $name;  //string
    public $milestones; //array
    public $recent; //flag
    public $show;//flag
    public $type;//type
}

class Project
{
    public $name;  //string
    public $date;  // date
    public $subprojects; //array
    public $link; 
    public $last_updated;// Last updated
    public $recent; // flag
}

//$engineer_tags = array("asadz", "mehreen", "awaisa", "farhan","asada","ehtsham","awaisf");

$engineer_tags = array(

    "asadz" => "Asad Zia", 
    "mehreen" => "Mehreen", 
    "awaisa" => "Awais Anwar", 
    "asada" => "Asad Ali",
    "ehtsham" => "Ehtsham",
    "awaisf" => "Awais Fazal" 
);


function SaveProjectsEngineer($projects,$engineer)
{
    $subproject_backlog = " ";
    $milestone_backlog = " ";

    
    $file = fopen("generated/".$engineer.".xml","w");
    fwrite($file,'<xml Version="1.0">'.PHP_EOL);

    $timestamp = strtotime(INTERVAL_GANTT,strtotime('today'));
    fwrite($file,'<project name="'.$engineer.'" date="'.date('d.m.y', $timestamp).'">'.PHP_EOL);


    foreach ($projects as $project)
    {
        if($project->last_updated < $timestamp)
            continue;

        $partition_log = '<subproject name="'.$project->name.'" type="partition"/>'.PHP_EOL;

        foreach ($project->subprojects as $subproject)
        {
            if($subproject->show)
                $sp_backlog = '<subproject name="'.$subproject->name.'" show="true">'.PHP_EOL;
            else
                $sp_backlog = '<subproject name="'.$subproject->name.'" show="false">'.PHP_EOL;
        
            foreach ($subproject->milestones as $milestone)
            {
                $milestone_backlog = '<milestone name="'.$milestone->name.'" status="'.$milestone->status.'">'.PHP_EOL;
                foreach ($milestone->logs as $log)
                {
                    if($log->engineer == $engineer)
                    {   

                        if(strlen($partition_log)>10)
                        {
                            fwrite($file,$partition_log);
                            $partition_log = "Done";       
                        }
                        
                        if(strlen($sp_backlog)>10)
                        {
                            fwrite($file,$sp_backlog);
                            $sp_backlog = "Done";       
                        }

                        if(strlen($milestone_backlog)>10)
                        {
                            fwrite($file,$milestone_backlog);
                            $milestone_backlog = "Done";       
                        }
                        fwrite($file,'<'.$log->engineer.' date="'.$log->date.'" days="'.$log->days.'" log="'.$log->msg.'"/>'.PHP_EOL);        
                    }
                }
                if($milestone_backlog == "Done")
                {
                    fwrite($file,'</milestone>'.PHP_EOL);
                    $milestone_backlog = "";       
                }
            }
            
            if($sp_backlog == "Done")
            {
                fwrite($file,'</subproject>'.PHP_EOL);
                $sp_backlog = "";       
            }
        }
    }
    fwrite($file,'</project>'.PHP_EOL);
    fwrite($file,'</xml>'.PHP_EOL);
    fclose($file);
}


function GetLastWeekDate()
{
    date_default_timezone_set('Asia/Karachi');
    $date = new DateTime();
    //echo $date->format('d:m:y');
    //echo "*";
    //echo $date->format('U');
    //echo "*";

    
    $date->modify('monday this week');
    $date->modify('-1 week'); // to get the last week's first date
    $interval = $date->format('U');
    return $interval;
}


function SaveLastWeekProjectsXML($projects)
{
    //GetLastWeekDate
    $file = fopen("generated/last-projects.xml","w");
    fwrite($file,'<xml Version="1.0">'.PHP_EOL);

    $timestamp = strtotime(INTERVAL_GANTT,strtotime('today'));
    fwrite($file,'<project name="Weekly Activities" date="'.date('d.m.y', $timestamp).'">'.PHP_EOL);


    foreach ($projects as $project)
    {
        if(!$project->recent)
            continue;   


        fwrite($file,'<subproject name="'.$project->name.'" type="partition"/>'.PHP_EOL);
        
        foreach ($project->subprojects as $subproject)
        {
            if(!$subproject->recent)
                continue;
            if($subproject->show)
                fwrite($file,'<subproject name="'.$subproject->name.'" show="true">'.PHP_EOL);
            else
                fwrite($file,'<subproject name="'.$subproject->name.'" show="false">'.PHP_EOL);
            foreach ($subproject->milestones as $milestone)
            {
                 if(!$milestone->recent)
                    continue;

                fwrite($file,'<milestone name="'.$milestone->name.'" status="'.$milestone->status.'">'.PHP_EOL);
                foreach ($milestone->logs as $log)
                {
                    if(!$log->recent)
                        continue;
                    fwrite($file,'<'.$log->engineer.' date="'.$log->date.'" days="'.$log->days.'" log="'.$log->msg.'"/>'.PHP_EOL);        
                }
                fwrite($file,'</milestone>'.PHP_EOL);
            }
            fwrite($file,'</subproject>'.PHP_EOL);
        }
    }
   
    fwrite($file,'</project>'.PHP_EOL);
    fwrite($file,'</xml>'.PHP_EOL);
    fclose($file);
}


function SaveProjectsXML($projects)
{
    $file = fopen("generated/projects.xml","w");
    fwrite($file,'<xml Version="1.0">'.PHP_EOL);

    $timestamp = strtotime(INTERVAL_GANTT,strtotime('today'));
    fwrite($file,'<project name="Weekly Activities" date="'.date('d.m.y', $timestamp).'">'.PHP_EOL);


    foreach ($projects as $project)
    {
        if($project->last_updated < $timestamp)
            continue;   
        fwrite($file,'<subproject name="'.$project->name.'" type="partition"/>'.PHP_EOL);
        
        foreach ($project->subprojects as $subproject)
        {
            if($subproject->show)
                fwrite($file,'<subproject name="'.$subproject->name.'" show="true">'.PHP_EOL);
            else
                fwrite($file,'<subproject name="'.$subproject->name.'" show="false">'.PHP_EOL);
            foreach ($subproject->milestones as $milestone)
            {

                fwrite($file,'<milestone name="'.$milestone->name.'" status="'.$milestone->status.'">'.PHP_EOL);
                foreach ($milestone->logs as $log)
                {

                    fwrite($file,'<'.$log->engineer.' date="'.$log->date.'" days="'.$log->days.'" log="'.$log->msg.'"/>'.PHP_EOL);        
                }
                fwrite($file,'</milestone>'.PHP_EOL);
            }
            fwrite($file,'</subproject>'.PHP_EOL);
        }
    }
   
    fwrite($file,'</project>'.PHP_EOL);
    fwrite($file,'</xml>'.PHP_EOL);
    fclose($file);
}

function SavePieChartEngineer($projects,$engineer)
{
    global $engineer_tags;
    include "libchart/libchart/classes/libchart.php";
    $chart = new PieChart();
    $dataSet = new XYDataSet();


    foreach ($projects as $project)
    {
        if($project->$engineer > 0)
        {
            $dataSet->addPoint(new Point($project->name.'('.(string)$project->$engineer.' Days)', $project->$engineer));
        }
    }
    $chart->setDataSet($dataSet);
    $chart->setTitle($engineer_tags[$engineer]." Projects");
    $chart->render("generated/".$engineer.".png");
}

function SavePieChartAllProjects($projects)
{
    include "libchart/libchart/classes/libchart.php";

    $chart = new PieChart();

    $dataSet = new XYDataSet();

    foreach ($projects as $project)
    {
        if($project->total_logdays >2 )
            $dataSet->addPoint(new Point($project->name.'('.(string)$project->total_logdays.' Days)', $project->total_logdays));
    }    
    $chart->setDataSet($dataSet);
    $chart->setTitle("All Projects");
    $chart->render("generated/all-projects.png");
}

function SaveLineChartProjects($projects)
{
    $date_labels = array();
    
    foreach ($projects as $project) 
    {

        foreach ($project->date_labels as $key => $value) 
         {
            
            if (array_key_exists($key,$date_labels))
                $date_labels[$key] += $value;
            else
                $date_labels[$key] = $value;
            
         }
    }
    ksort($date_labels);
    
    include "libchart/libchart/classes/libchart.php";

    $chart = new LineChart();

    $dataSet = new XYDataSet();

    $today = new DateTime("now");
     
    foreach ($date_labels as $key => $value) {
        $nkey = InverseMap($key);
                
        //$date = new DateTime($nkey);
        //$date = strtodate('mmddyy',$nkey);

        //echo $today;
        //echo $date->format('m.d.y');
        //$interval = $date->diff($today);
        //var_dump($today < $date);
        //echo $interval->format('%R%a days');

        $dataSet->addPoint(new Point($nkey, $value));
        //echo $nkey." ".$value."<br>";
        //echo  $nkey.' '.$key.' '.$value.'<br>'; 
    }

    $chart->setDataSet($dataSet);

    $chart->setTitle("Team Work Load");
    $chart->render("generated/workload.png");


}
function SavePieChartLastWeekProjects($projects)
{
    include "libchart/libchart/classes/libchart.php";

    $chart = new PieChart();

    $dataSet = new XYDataSet();

    foreach ($projects as $project)
    {
        if(!$project->recent)
            continue;
        $dataSet->addPoint(new Point($project->name.'('.(string)$project->week_logdays.' Days)', $project->week_logdays));
        //$dataSet->addPoint(new Point("Mozilla Firefox (80)", 80));

    //echo $project->name."    ".(string)round($project->week_logdays/35*100).'<br>';     
    }    
   


    //$dataSet->addPoint(new Point("Mozilla Firefox (80)", 80));
    //$dataSet->addPoint(new Point("Konqueror (75)", 75));
    //$dataSet->addPoint(new Point("Opera (50)", 50));
    //$dataSet->addPoint(new Point("Safari (37)", 37));
    //$dataSet->addPoint(new Point("Dillo (37)", 37));
    //$dataSet->addPoint(new Point("Other (72)", 70));
    $chart->setDataSet($dataSet);

    $chart->setTitle("Last Week Projects");
    $chart->render("generated/last-projects.png");
}


function InverseMap($key)
{
    $code = "";
    for($i=0;$i<strlen($key);$i++)
    {
        if($key[$i] == 'A')
            $code[$i] = '0';
        else if($key[$i] == 'B')
            $code[$i] = '1';
        else if($key[$i] == 'C')
            $code[$i] = '2';
        else if($key[$i] == 'D')
            $code[$i] = '3';
        else if($key[$i] == 'E')
            $code[$i] = '4';
        else if($key[$i] == 'F')
            $code[$i] = '5';
        else if($key[$i] == 'G')
            $code[$i] = '6';
        else if($key[$i] == 'H')
            $code[$i] = '7';
        else if($key[$i] == 'I')
            $code[$i] = '8';
        else if($key[$i] == 'J')
            $code[$i] = '9';
        
    }

    return implode("",$code);

}
function KeyMapper($key)
{
    $code = "";
    for($i=0;$i<strlen($key);$i++)
    {
        if($key[$i] == '0')
            $code[$i] = 'A';
        else if($key[$i] == '1')
            $code[$i] = 'B';
        else if($key[$i] == '2')
            $code[$i] = 'C';
        else if($key[$i] == '3')
            $code[$i] = 'D';
        else if($key[$i] == '4')
            $code[$i] = 'E';
        else if($key[$i] == '5')
            $code[$i] = 'F';
        else if($key[$i] == '6')
            $code[$i] = 'G';
        else if($key[$i] == '7')
            $code[$i] = 'H';
        else if($key[$i] == '8')
            $code[$i] = 'I';
        else if($key[$i] == '9')
            $code[$i] = 'J';
        
    }

    //echo $key.'<br>';
    //echo implode("",$code).'<br>';
    return implode("",$code);
}

function ReadProjectData($filename_with_path)
{
    global $engineer_tags;

    $project_tag = PROJECT_TAG;
    $subproject_tag = SUBPROJECT_TAG;
    $milestone_tag = MILESTONE_TAG;
    $log_tag = LOG_TAG;
    
    

    $filename = basename($filename_with_path); 
    //echo $filename;
    $data = file_get_contents($filename_with_path);
    $xml = new SimpleXMLElement($data);
  
    $project = new Project();
    $project->name = $xml->{$project_tag}['name'];
    $project->date = $xml->{$project_tag}['date'];
    $project->link = $filename;
    $project->last_updated = 0;
    $project->subprojects = array();
    $project->total_logdays = 0;
    $project->week_logdays = 0;
    $project->date_labels = array();
    
    foreach ($engineer_tags as $key => $value)    
        $project->$key = 0;

    
    for ($i = 0; $i < sizeof($xml->{$project_tag}->{$subproject_tag}); $i++)
    {
        $subproject =  new SubProject();
        
             
        $subproject->name = $xml->{$project_tag}->{$subproject_tag}[$i]['name'];
        //$subproject->name = $xml->{$project_tag}->{'{$subproject}' . $i}['name'];
        $subproject->show = $xml->{$project_tag}->{$subproject_tag}[$i]['show'] == 'false'? false: true;
        $subproject->type = $xml->{$project_tag}->{$subproject_tag}[$i]['type'] == 'partition' ? 'partition':'sub project';
        if($subproject->type == 'partition')
            $subproject->show = false;

        $subproject->milestones = array();

        for ($j = 0; $j < sizeof($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}); $j++)
        {
            $milestone = new Milestone();
            $milestone->name = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]['name'];
            if (isset($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]['assignee'])) 
                $milestone->assignee = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]['assignee'];
            else
                $milestone->assignee = "   ";

            if (isset($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]['status'])) 
                $milestone->status = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]['status'];
            else
                $milestone->status = "In Progress";
            $milestone->logs = array();
            

            //for($k=0; $k < sizeof($engineer_tags); $k++)
            foreach ($engineer_tags as $key => $value)    
            {
                for ($l = 0; $l < sizeof($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->$key); $l++)
                {
                    $log = new Log();
                    
                    $log->engineer = $key;
                    $log->days = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l]['days'];
                    $log->msg  = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l][$log_tag];
                    $log->date = $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l]['date'];

                    if (isset($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l]['workload']))
                    {
                        $log->workload =  $xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l]['workload'];
                    }
                    else // if not set then default to true
                        $log->workload =  "true";

                    

                    $logdate = strtotime($xml->{$project_tag}->{$subproject_tag}[$i]->{$milestone_tag}[$j]->{$key}[$l]['date']);
                    if($project->last_updated < $logdate)
                        $project->last_updated = $logdate;


                    
                    $interval = GetLastWeekDate();
                    //$interval = strtotime(INTERVAL,strtotime('today'));
                    if($logdate >= $interval)
                    {
                        $milestone->recent = true;
                        $log->recent = true;
                        $subproject->recent = true;
                        $project->recent = true;
                        $project->week_logdays += $log->days;    
                    }   
                    $project->total_logdays += $log->days;
                    $project->$key +=  $log->days;

////////////////////////////////////////////////////////////////////////////////

                    $date = new DateTime();
                    $date->setTimestamp($logdate);
                    //$date= date("d/m/Y", $logdate);
                    $date->modify('friday this week');
                    $date_label =  $date->format('ymd');
                    $date_label = KeyMapper($date_label);
                    //$date->getTimestamp($logdate);
                    if($log->workload !=  "false")
                    {
                        if (array_key_exists($date_label,$project->date_labels))
                            $project->date_labels[$date_label] += $log->days;
                        else
                            $project->date_labels[$date_label] = $log->days;
                    }
                    //else
                    //    echo "No work load";
                    //echo date("d-m-y", strtotime($logdate));
                    
//date_default_timezone_set('Asia/Karachi');
//$date = new DateTime();

  //  $date->modify('monday this week');

///////////////////////////////////////////////////////////////////////////////////
                    array_push($milestone->logs,$log);        
                }         
            }
            array_push($subproject->milestones,$milestone);
        }    
        array_push($project->subprojects,$subproject);
    }

   ksort($project->date_labels);
    return $project;
}

function ReadProjectNamesFromDir($dirname)
{
    $projectnames = array();
    //echo $dir;
    $dir = new DirectoryIterator($dirname);
    foreach ($dir as $fileinfo) 
    {
        if (!$fileinfo->isDot()) 
        {
            $filename = $fileinfo->getFilename();
            $filename_with_path = $dirname."//".$filename;
            //echo $filename_with_path;
            //echo "<br>";
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
             
            if($ext != 'xml')
                continue;
            
            array_push($projectnames,$filename_with_path);

        }    

    }
    return $projectnames;
}

function ReadProjectFromDir($dir)
{
    $projects =  array();
    $dir = new DirectoryIterator($dir);

    foreach ($dir as $fileinfo) 
    {
        if (!$fileinfo->isDot()) 
        {
            $filename = $fileinfo->getFilename();
            $filename_with_path = '.\\xml\\'.$filename;
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
             
            if($ext != 'xml')
                continue;
            $project = ReadProjectData($filename_with_path);
            array_push($projects,$project);

        }    

    }
    return $projects;
}


function CompareProjects($a,$b)
{
    if ($a->last_updated == $b->last_updated) {
        return 0;
    }
    return ($a->last_updated < $b->last_updated) ? 1 : -1;

}

//$projects = ReadProjectFromDir("xml");
//usort($projects, "CompareProjects");


//$project = ReadProjectData("xml/2014.12-ReadyStart-Release.xml");   


/*
foreach ($projects as $project)
{
    echo $project->name.'<br>';
    echo $project->date.'<br>';
    echo $project->link.'<br>';

    foreach ($project->subprojects as $subproject)
    {
        if($subproject->recent == false)
            continue;
        echo $subproject->name.'<br>';
        foreach ($subproject->milestones as $milestone) 
        {
            if($milestone->recent == false)
                continue;
            echo $milestone->name.'<br>';
            foreach ($milestone->logs as $log)    
            {
                if($log->recent == false)
                    continue;
                echo $log->engineer.'<br>';;
                echo $log->msg.'<br>';
                echo $log->date.'<br>';
            }
        }  
    }    
}
*/




?>

